<template>
  <div class="suggestion">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
    >
      <van-cell 
      v-for="(item,index) in list" 
      :key="index" 
      icon="search"
      @click="toSuggestion(item,index)"
      >
      <span v-html="Highlight(item)"></span>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import { getSuggesTions} from '@/service/getDate'
import { debounce } from 'lodash'
export default {
    name: 'suggeStion',
    data() {
    return {
      list: [],
      loading: false,
      finished: false,
      resultText: false, // 文本搜索结果是否为零
    };
  },
    props: {
      resultValue: {
        type:String,
        required: true,
      }
    },
    watch: {
     // 侦听输入框的值是否有发现改变
     resultValue: {
      handler: debounce(function(value) {
        this.onLoad(value)
      },500),
      immediate: true
     },
    },
    methods: {
     async onLoad(q) {
        try {
          const {data} = await getSuggesTions({
            q: q
          })
          const {options} = data.data
          this.list.push(...options)
          this.finished = true
          console.log(options)
          this.resultText = false
         
        } catch(err) {
          console.log(err)
        }
      },
      Highlight(item) {
       if (item === null) {
        this.list = null
        this.resultText = true
        return
       }
        const HighlightHtml = `<span class="HighlightColor">${this.resultValue}</span>`

        // 使用正则表达式的构造函数 把需要替换的值筛选出来
        const res = new RegExp(this.resultValue, 'gi')

        // 最后替换文本，把更改后的html返回DOM页面
        return item.replace(res,HighlightHtml)
      },
      toSuggestion(val) {
        this.$emit('toSuggestion', val)
      }
    },
}
</script>

<style lang="scss" scoped>
  .suggestion {
   /deep/ .HighlightColor {
      color: #ed3651;
    }
  }
</style>